#include <graphics.h>
#include "food.h"
#include "snake.h"

void Snake::add(void)
{
	if (direction == UP)
		y_head += LENGTH;
	else if (direction == DOWN)
		y_head -= LENGTH;
	else if (direction == LEFT)
		x_head += LENGTH;
	else if (direction == RIGHT)
		x_head -= LENGTH;

	body.push_back(create_body(x_head, y_head, direction));
}

void Snake::add(Food &food)
{
	int x_tail = body[body.size() - 1].x;
	int y_tail = body[body.size() - 1].y;
	key_t direction_temp = body[body.size() - 1].direction_now;
	if (direction_temp == UP)
		y_tail += LENGTH;
	else if (direction_temp == DOWN)
		y_tail -= LENGTH;
	else if (direction_temp == LEFT)
		x_tail += LENGTH;
	else if (direction_temp == RIGHT)
		x_tail -= LENGTH;

	body.push_back(create_body(x_tail, y_tail, body[body.size() - 1].direction_now));
	--food.box_left;
}


bool Snake::move(key_t direction_now)
{
	if (check_move_available(direction_now))
	{
		body[0].move(direction_now);
		body[0].direction_now = direction_now;
		for (unsigned i = 1; i < body.size(); ++i)
		{
			body[i].move();
			body[i].redirect(body[i - 1]);
		}
		direction = direction_now;
		return true;
	}
	else
		return false;
}

void Snake::draw()
{
	for (unsigned i = 0; i < body.size(); ++i)
	{
		body[i].draw();
	}
}

bool Snake::check_collision(void)
{
	if (body[0].x < 0 || body[0].x >= SCREEN_WIDTH)
		return true;
	else if (body[0].y < 0 || body[0].y >= SCREEN_HEIGHT)
		return true;
	else
	{
		bool collision = false;
		for (unsigned i = 1; i < body.size(); ++i)
			if (body[0].x == body[i].x && body[0].y == body[i].y)
			{
				collision = true;
				break;
			}
		return collision;
	}
}

void Snake::check_collision(Food &food)
{
	if (body[0].x == food.x && body[0].y == food.y)
	{
		food.create_food(*this);
		add(food);
	}
}

Snake_body Snake::create_body(int x, int y, key_t direction_temp)
{
	Snake_body body_now(x, y, direction_temp);
	return body_now;
}

bool Snake::check_move_available(key_t direction_check)
{
	if (direction == LEFT && direction_check == RIGHT)
		return false;
	else if (direction == RIGHT && direction_check == LEFT)
		return false;
	else if (direction == UP && direction_check == DOWN)
		return false;
	else if (direction == DOWN && direction_check == UP)
		return false;
	else
		return true;
}